package com.example.runningdemo.designModel;

/**
 * @program: Running-Demo
 * @description: 双重锁
 * @author: kangwei
 * @create: 2024-08-07 09:17
 **/
public class DoubleLockSingleton {

    // 定义实例变量
    private static DoubleLockSingleton INSTANCE;

    private DoubleLockSingleton() {

    }

    // 获取实例对象
    public static DoubleLockSingleton getInstance() {
        if (null == INSTANCE) {
            synchronized (DoubleLockSingleton.class) {
                if (null == INSTANCE) {
                    return new DoubleLockSingleton();
                }
            }
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            System.out.println(getInstance());
            try {
                Thread.sleep(20000L);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "thread1");
        Thread thread2 = new Thread(() -> {
            System.out.println(getInstance());
        }, "thread2");
        thread1.start();
        thread2.start();
    }
}
